<template>
  <el-dialog v-model="visible" :title="title" width="1200" show-footer show-zoom resize :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="form" label-align="right" label-width="60" size="default"
        label-position="top">
        <el-row :gutter="20">
          <el-col :span="8" v-if="handleType != 'add'">
            <el-form-item label="组合单号">
              {{ form.warehouse_combination_order_no }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouse_id">
              <SelectWarehouse style="width: 400px;" v-model="form.warehouse_id" :disabled="form.id" placeholder="请输入仓库"
                @change="changeWarehouse">
              </SelectWarehouse>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="warehouse_id">
              <el-input v-model="form.remark" placeholder="备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <vxe-table :data="form.detail" :round="true" height="500">
        <vxe-column title="组合SKU" width="160">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.combo_sku }}</template>
            <el-input v-else v-model="row.combo_sku" placeholder="组合SKU" @change="changeSkU(row)"
              :disabled="handleType == 'out'" />
          </template>
        </vxe-column>
        <vxe-column field="name" title="货主">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.owner_name }}</template>
            <select-personnel v-else v-model="row.owner_id" placeholder="货主"
              :disabled="handleType == 'view' || disabled"></select-personnel>
          </template>
        </vxe-column>

        <vxe-column title="组合数量">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.combo_num }}</template>
            <el-input v-else v-model="row.combo_num" placeholder="组合数量" />
          </template>
        </vxe-column>
        <vxe-column title="组合货位">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.location_code }}</template>
            <el-select v-else v-model="row.location_id" placeholder="货位" :disabled="handleType == 'view' || disabled">
              <el-option v-for="item in locationAllData" :key="item.location_id" :label="item.location_code"
                :value="item.location_id">
              </el-option>
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="name" title="子SKU">
          <template #default="{ row }">
            <div v-for="(item, index) in row.combination_list" :key="index">{{ item.sku }}</div>
          </template>
        </vxe-column>
        <vxe-column field="name" title="货位">
          <template #default="{ row }">
            {{ row.sku_cn_title || '--' }}
          </template>
        </vxe-column>
        <!-- <vxe-column field="name" title="可用库存">
          <template #default="{ row }">
            <div v-for="(item, index) in row.combination_list" :key="index">{{ item.num }}</div>
          </template>
        </vxe-column> -->
        <vxe-column field="name" title="需求数">
          <template #default="{ row }">
            <div v-for="(item, index) in row.combination_list" :key="index">{{ item.need_num || (item.quantity * row.combo_num || 0) }}
            </div>
          </template>
        </vxe-column>
        <vxe-column field="opearn" title="操作" width="100" v-if="handleType != 'view'">
          <template #default="{ row, rowIndex }">
            <el-link class="mr-2" size="small" type="primary" @click="addRow">新增</el-link>
            <el-link size="small" type="danger" @click="deleteRow(rowIndex)">删除</el-link>
          </template>
        </vxe-column>
      </vxe-table>
    </template>

    <template #footer>
      <template v-if="handleType == 'view'">
        <div class="flex justify-center py-2">
          <el-button type="" @click="close">关 闭</el-button>
        </div>
      </template>
      <div class="flex justify-center py-2" v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save(formRef)">保 存</el-button>
      </div>

    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { getInventoryCountDetail, saveInventoryCount } from '../api/index'
import { getComboSKUInfo, getLocationData } from '@/api/public'
import { reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import SelectWarehouse from '@/components/SelectWarehouse'

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(['query'])

const data = reactive({
  form: {},
  title: '新增',
  handleType: null,
  rules: {
    warehouse_id: [{
      required: true, message: '请选择仓库', trigger: 'blur'
    }]
  },
  locationAllData: []
})
const { form, title, handleType, rules, locationAllData } = toRefs(data)

const statusMap = new Map([
  ['add', '新增'],
  ['edit', '编辑'],
  ['view', '查看'],
])

const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {
    detail: [
      {
        sku: "",//sku
        custom_sku: "",//自定义sku
        base_sku_code: "",//商品编码
        location_id: "",//货位编码
        remark: "",//备注
        location: []
      }
    ]
  }
}

onMounted(() => {
  initForm()
})

const getDetail = async (id) => {
  try {
    const res = await getInventoryCountDetail({
      id
    })
    res.data.detail.forEach(element => {
      element.combination_list = element.sku_detail
    });
    form.value = res.data

  } catch (e) {
    throw Error(e)
  }
}

const addRow = async () => {
  form.value.detail.push({
    sku: "",//sku
    custom_sku: "",//自定义sku
    base_sku_code: "",//商品编码
    location_code: "",//货位编码
    remark: "",//备注
    locationList: []
  })
}

const deleteRow = (index) => {
  if (form.value.detail.length <= 1) return
  form.value.detail.splice(index, 1)
}


const changeSkU = async (row) => {
  if (!row.combo_sku) {
    ElMessage.error('输入sku')
    return
  }
  if (!form.value.warehouse_id) {
    ElMessage.error('请选择仓库')
    return
  }
  try {
    const res = await getComboSKUInfo({
      combo_sku: row.combo_sku,
      warehouse_id: form.value.warehouse_id,
    })
    if (res.data) {
      row.sku = res.data.sku
      row.combination_list = res.data.combination_list
    } else {
      ElMessage.error('没有组合SKU信息')

    }

  } catch (e) {
    throw Error(e)
  }
}

const changeWarehouse = (val) => {
  if (val) {
    getLocationList()
  }
}

const getLocationList = async () => {

  try {
    const res = await getLocationData({
      warehouse_id: form.value.warehouse_id
    })
    locationAllData.value = res.data.map(i => {
      i.location_id = i.id
      return i
    })
  } catch (e) {
    throw Error(e)
  }
}

const save = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      const formData = form.value
      formData.detail.forEach(element => {
        element.combination_list.forEach(v => {
          v.need_num = (element.combo_num || 0) * v.quantity
        })
      });
      if (formData.id) {
        updateInventoryCount(formData)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      } else {
        saveInventoryCount(formData)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      }
    }
  })
}

const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.borderNone {
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none
  }
}</style>
